package com.huike.framework.web.service;

import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import com.huike.common.constant.Constants;
import com.huike.common.core.domain.model.LoginUser;
import com.huike.common.core.redis.RedisCache;
import com.huike.common.exception.CustomException;
import com.huike.common.exception.user.CaptchaException;
import com.huike.common.exception.user.CaptchaExpireException;
import com.huike.common.exception.user.UserPasswordNotMatchException;
import com.huike.common.utils.MessageUtils;
import com.huike.framework.manager.AsyncManager;
import com.huike.framework.manager.factory.AsyncFactory;

/**
 * 登录校验方法
 * 
 * 
 */
@Component
public class SysLoginService {
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    /**
     * 登录验证
     * 
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid) {
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null)//日志打印验证码过期
        //1.me是静态方法，它返回了一个me,而me创建了一个AsyncManager对象
            //2.对象asyncManager执行execute(TimerTask task){ executor.schedule(task, OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS) }方法
            //3.execute方法:executor是ScheduledExecutorService类型对象,是基于线程池设计的定时任务类,每个调度任务都会分配到线程池中的一个线程去执行,
                           //提供了只运行一次的延迟任务方法schedule，只在延迟时间后 运行一次任务;(任务,10,设置时间单位为毫秒)
            //4.execute方法的形参是定时器任务(TimerTask)类型.实现了Runnable接口,需要重写run方法; Java JDK提供的Timer类就是一个很好的工具，通过简单的API调用，我们就可以实现定时任务。
            //5.execute方法的实参recordLogininfor方法中返回了TimerTask参数,并重写了其run方法
            //schedule方法的参数为定时器任务(TimerTask)；该参数由异步工厂（AsyncFactory，用来产生任务）的recordLogininfor方法获得
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            throw new CaptchaExpireException();//LOGIN_FAIL = "Error" ,执行recordLogininfor-TimerTask的重写run方法-else if逻辑
        }
        if (!code.equalsIgnoreCase(captcha))//日志打印验证码不等
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }
        // 用户验证
        Authentication authentication = null;
        try {
            /**
             * ！！！看我看我看我！！！
             * 看我少走弯路，获取用户对象的时候，会去调用下面的这个方法查询用户对象
             * UserDetailsServiceImpl.loadUserByUsername
             */
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            System.out.println("username "+username+" -----password "+password);
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        }catch (Exception e) {
            e.printStackTrace();
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new CustomException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 生成token
        return tokenService.createToken(loginUser);
    }
}
